package com.sgb.kjwl.view.ui.fragment.self.company

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentEnquiryBinding
import com.sgb.kjwl.databinding.ItemAgentEnquiryBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.sgb.kjwl.model.entity.self.AgentEnquiryEntity
import com.sgb.kjwl.view.event.self.RefreshUnReadNumEvent
import com.sgb.kjwl.viewmodel.self.company.EnquiryViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.dialog.RoundCornerDialog
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.DateUtils
import com.swgk.core.util.MToast
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import javax.inject.Inject

class AgentEnquiryFragment : AppLazyFragment() {

    private lateinit var mBinding : FragmentEnquiryBinding

    private var mNo = ""
    private lateinit var mAdapter : EnquiryAdapter

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    @Inject
    lateinit var mViewModel : EnquiryViewModel

    companion object{
        const val TAG = "enquiryFragment"
        const val KEY_NO = "key_no"
        fun newInstance(no : String)  : AgentEnquiryFragment {
            val fragment = AgentEnquiryFragment()
            val bundle = Bundle()
            bundle.putString(KEY_NO, no)
            fragment.arguments = bundle
            return fragment
        }
    }

    override fun setupFragmentComponent(appComponent: AppComponent?) {
        super.setupFragmentComponent(appComponent)
        DaggerSelfFragComponent.builder().appComponent(appComponent)
            .selfFragModule(SelfFragModule()).build().inject(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (arguments != null){
            mNo = requireArguments().getString(AgentAgreementFragment.KEY_NO)!!
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_enquiry, container, false)
        return mBinding.root
    }

    override fun initView() {
        super.initView()
        initRecyclerView()


        mViewModel.shopList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (isLoadMore){
                mAdapter.addData(it)
            } else {
                mAdapter.setNewData(it)
            }
        })
        mViewModel.readPosition.observe(this, {
            if (it != null){
                MainScope().launch(Dispatchers.Main) {
                    delay(800)
                    mAdapter.remove(it)
                    EventBus.getDefault().postSticky(RefreshUnReadNumEvent.make())
                }
            }
        })
    }

    override fun onLazyLoad() {

        isLoadMore = false
        getData()
    }

    fun getData(){
        if (mNo != "-1" ) {//说明有权限
            mViewModel.getShopEnquiryList(isLoadMore)
        }
    }


    @SuppressLint("UseRequireInsteadOfGet")
    private fun initRecyclerView() {
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                getData()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                getData()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = EnquiryAdapter(context!!, R.layout.item_agent_enquiry)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp1), resources.getColor(R.color.color_main_bg)
            )
        )
        mAdapter.setCallBack(object : ClickCallBack{
            override fun clickContact(phone: String) {
                showDialog(phone)
            }

            override fun clickItem(item: AgentEnquiryEntity?, position: Int) {
                if (item == null){
                    return
                }
                mViewModel.saveUserReadAgent(item.id, position)
                if (item.isDelete()){
                    MToast.showToast(context, "询价单已删除！")
                    return
                }
                mViewModel.getPriceCheckDetail(context!!, item.no, item.status,0)

            }

        })
    }

    /**
     * 展开客服弹窗
     */
    private fun showDialog(phone : String) {
        val view = View.inflate(activity, R.layout.dialog_two_btn, null)
        val roundCornerDialog = RoundCornerDialog(
            activity, 0, 0, view, R.style.RoundCornerDialog
        )
        roundCornerDialog.show()
        roundCornerDialog.setCanceledOnTouchOutside(false) // 设置点击屏幕Dialog不消失
        //roundCornerDialog.setOnKeyListener(keylistener);//设置点击返回键Dialog不消失
        val tv_message = view.findViewById<TextView>(R.id.tv_message)
        val tv_title = view.findViewById<TextView>(R.id.tv_title)
        val tv_logout_confirm = view.findViewById<TextView>(R.id.tv_logout_confirm)
        val tv_logout_cancel = view.findViewById<TextView>(R.id.tv_logout_cancel)
        tv_title.text = "联系客服"
        tv_title.visibility = View.VISIBLE
        tv_message.text = phone
        tv_logout_confirm.text = "拨打"
        //确定
        tv_logout_confirm.setOnClickListener {
            val intent = Intent(Intent.ACTION_DIAL)
            val data = Uri.parse("tel:$phone")
            intent.data = data
            startActivity(intent)
        }
        //取消
        tv_logout_cancel.setOnClickListener { //关闭弹窗
            roundCornerDialog.dismiss()
        }
    }



    class EnquiryAdapter(mContext : Context, @LayoutRes layoutId : Int) : BaseQuickAdapter<AgentEnquiryEntity, BaseViewHolder>(layoutId){
        private var mItemBinding : ItemAgentEnquiryBinding ?= null

        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_title_medium))

        private var mPriceColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_secondary_red))

        private var ssb : SpannableStringBuilder ?= null

        private var mCallBack : ClickCallBack ?= null

        fun setCallBack(callBack : ClickCallBack){
            mCallBack = callBack
        }
        override fun convert(helper: BaseViewHolder?, item: AgentEnquiryEntity?) {
            mItemBinding = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinding != null){
                mItemBinding!!.entity = item
                setColorSpan(mContext.resources.getString(R.string.enquiry_address, item!!.receiveAddr), mItemBinding!!.tvAddress)
                setColorSpan(mContext.resources.getString(R.string.offer_time, DateUtils.timestampToDateSecond(item.quoteTime)), mItemBinding!!.tvOfferTime)
                setColorSpan(mContext.resources.getString(R.string.enquiry_order_no, item.no), mItemBinding!!.tvOrderNo)
                setPriceColorSpan(mContext.resources.getString(R.string.enquiry_offer_price, item.totalPrice), mItemBinding!!.tvOfferPrice)
                mItemBinding!!.tvContact.setOnClickListener {
                  if (mCallBack != null){
                      mCallBack!!.clickContact(item.tel)
                  }
                }
                mItemBinding!!.tvStatus.text = if (item.status == "2") "生效中" else "已失效"
                mItemBinding!!.tvStatus.setBgColor(if (item.status == "2") R.color.color_secondary_blue else R.color.color_tab_three)
                mItemBinding!!.root.setOnClickListener {
                    if (mCallBack != null){
                        mCallBack!!.clickItem(item, helper.layoutPosition)
                    }
                }
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

        private fun setPriceColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mPriceColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

    }

    interface ClickCallBack{
       fun clickContact(phone : String)
       fun clickItem(item : AgentEnquiryEntity?, position : Int)
    }
}